/**
 * ©2013-2015 Alan L. Rights Reserved.
 */
package org.freedom.railhunter.service;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.codehaus.jackson.JsonNode;
import static org.freedom.railhunter.service.BaseService.DATA;
import static org.freedom.railhunter.service.BaseService.STATUS;
import static org.freedom.railhunter.service.BaseService.object_mapper;
import org.freedom.railhunter.util.HttpConnectionManager;
import org.freedom.railhunter.config.PathConfig;
import org.freedom.railhunter.model.AcceptDataType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Alan
 */
public class RandCodeService extends BaseService {
    
    private static final Logger logger = LoggerFactory.getLogger(RandCodeService.class);
    
    public static final String RAND = "rand";
    public static final String RAND_VALUE = "sjrand";
    
    private static RandCodeService  randCodeService;
    
    private RandCodeService() {
    }
    
    public static RandCodeService getInstance() {
        if (randCodeService == null) {
            randCodeService = new RandCodeService();
        }
        return randCodeService;
    }
    
     /**
     * 基于登录用户Cookie数据构建登陆验证码图片
     *
     * @param cookieData
     * @return
     */
    public File buildRandCodeImageFile(String FileNameSuffix, Map<String, String> cookieData) {
        File file = new File(System.getProperty("java.io.tmpdir") + File.separator + cookieData.get("JSESSIONID")
                + "." + FileNameSuffix + ".jpg");
        try {
            HttpResponse response = HttpConnectionManager.getHttpRequest(PathConfig.GET_PASS_CODE_PATH,
                    PathConfig.LOGIN_INIT_PATH, null, AcceptDataType.IMAGE, cookieData);
            HttpEntity entity = response.getEntity();
            try (InputStream instream = entity.getContent(); OutputStream out = new FileOutputStream(file)) {
                byte[] tmp = new byte[1];
                while ((instream.read(tmp)) != -1) {
                    out.write(tmp);
                }
            }
            logger.info("更新登录验证码图像:" + file.getAbsolutePath());
        } catch (IOException e) {
            logger.error("构建登陆验证码图片异常", e);
        }
        return file;
    }
    
    /**
     * 获取验证码字节数组
     * 
     * @param cookieData
     * @return 
     */
    public byte[] buildRandCodeImageBytes(Map<String, String> cookieData) {
        try {
            HttpResponse response = HttpConnectionManager.getHttpRequest(PathConfig.GET_PASS_CODE_PATH,
                    PathConfig.LOGIN_INIT_PATH, null, AcceptDataType.IMAGE, cookieData);
            HttpEntity entity = response.getEntity();
            try (BufferedInputStream in = new BufferedInputStream(entity.getContent()); ByteArrayOutputStream out = new ByteArrayOutputStream()) {
                int b = in.read();
                while (b != -1) {
                    out.write(b);
                    b = in.read();
                }
                return out.toByteArray();
            }
        } catch (IOException e) {
            logger.error("构建登陆验证码图片异常", e);
        }
        return new byte[]{};
    }
    
    /**
     * 异步校验验证码
     * 
     * @param randCode
     * @param referer
     * @param cookieData
     * @return 
     */
    public boolean checkRandCodeAnsyn(String randCode, String referer, Map<String, String> cookieData) {
        try {
            List<NameValuePair> parameters = new ArrayList<>();
            parameters.add(new BasicNameValuePair(JSON_ATTR, ""));
            parameters.add(new BasicNameValuePair(RAND, RAND_VALUE));
            parameters.add(new BasicNameValuePair(RAND_CODE, randCode));
            
            String result = HttpConnectionManager.postHttpRequestAsString(PathConfig.CHECK_RAND_CODE_ANSYN_PATH,
                    referer, AcceptDataType.All, parameters, cookieData);
            JsonNode root = object_mapper.readTree(json_factory.createJsonParser(result));
            JsonNode statusNode = root.get(STATUS);
            if (statusNode != null && statusNode.getBooleanValue()) {
                JsonNode dataNode = root.get(DATA);
                return dataNode != null && "Y".equals(dataNode.getTextValue());
            }
        } catch (IOException e) {
            logger.error("异步校验验证码异常", e);
        }
        return false;
    }
}
